package com.lwd1513.designPattern.factory.proxy;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: 刘东（挂兰）
 * @Date: 2023/11/18 23:48:56
 * @Description: cglib动态代理针对 类要有父类
 */
public class TestCglibProxy {
    public static void main(String[] args) {
        RoleService roleService = new RoleServiceImpl();
        roleService.select();
        //1. 创建一个工具类
        Enhancer enhancer = new Enhancer();
        //2. 设置父类
        enhancer.setSuperclass(roleService.getClass());
        //3. 设置回调函数 --增强的操作
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println("Cglib代理模式 ~~ 开始");
                Object returnVal = method.invoke(roleService, args);
                System.out.println("Cglib代理模式 ~~ 提交");
                return returnVal;
            }
        });
        //4. 创建子类对象，即代理对象
        RoleService roleServiceProxy = (RoleService) enhancer.create();
        roleServiceProxy.select();

    }
}
